//
//  EMMHomePageViewController.m
//  EMMApp
//
//  Created by Mac on 16/4/26.
//  Copyright © 2016年 YiXun. All rights reserved.
//

#import "EMMHomePageViewController.h"
#import "DealsRecordController.h"
/** ViewController
 *
 *  首页ViewController导入.h文件
 */
#import "NextReminderViewController.h"      //下次跟进提醒
#import "ExamineListViewController.h"       //审核
#import "EMMTouristsViewController.h"       //客户
#import "RemindViewController.h"            //提醒
#import "NoticeViewController.h"            //公告
#import "ProjectModel.h"                    //存项目列表Model
/** View
 *
 *  首页View导入.h文件
 */
#import "MenuLitsView.h"

/** Cell
 *
 *  首页Cell导入.h文件
 */
#import "HomePageCell.h"
#import "HomeCell.h"

/** Api
 *
 *  首页Api调用导入.h文件
 */
#import "GetProjectBusinessListApi.h"
#import "SignBackMoneyController.h"
#import "TouristsWebController.h"
#import <ReactiveObjC.h>

@interface EMMHomePageViewController ()<UITableViewDelegate,UITableViewDataSource>

//判断yes 或者 no
@property (nonatomic, assign) BOOL isShowUI;

//创建UITableView
@property (nonatomic, strong) UITableView *homeTableView;

//数据源数组
@property (nonatomic, strong) NSMutableArray *dataArr;

//导航
@property (nonatomic, strong) MenuLitsView *menu;

//导航数组
@property (nonatomic, strong) NSMutableArray *menuList;

//数组导航
@property (nonatomic, strong) NSMutableArray *menuArr;

//GetProjectBusinessList - model
@property (nonatomic, strong) GetProjectBusinessList *getProjectBusinessList;

@end

@implementation EMMHomePageViewController

#pragma mark - 初始化调用
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    _homeTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, EMM_WIDTH, EMM_HEIGHT-SafeAreaTopHeight-SafeAreaTopHeight) style:UITableViewStylePlain];
    _homeTableView.delegate = self;
    _homeTableView.dataSource = self;
    _homeTableView.backgroundColor = [UIColor colorFromHexCode:@"#f7f7f7"];
    _homeTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_homeTableView];
    
}

#pragma mark 界面将要出现调用的函数 - 调用Api
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[EMMAppChecker sharedInstance] startCheckVgoUpdate];
    
    _menuList = [[NSMutableArray alloc] init];
    _menuArr = [[NSMutableArray alloc] init];
    _dataArr = [[NSMutableArray alloc] init];
    _menuList = [[NSMutableArray alloc] init];
    [self postGetProjectListApi];
    [self postGetProjectBusinessListApi];
    [self creatNavigationController];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self updateNavBar];
}

#pragma mark - 切换项目IAP
- (void)postGetProjectListApi {
    [_menuList removeAllObjects];
    [_menuArr removeAllObjects];
    GetProjectListApi *api = [[GetProjectListApi alloc] initWith];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        GetProjectListApi *result = (GetProjectListApi *)request;
        if (result.isSuccess) {
            GetProjectList *get = result.resultData;
            if (get.projectList.count > 0) {
                NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
                NSMutableArray *arr = [[NSMutableArray alloc] init];
                NSMutableArray *projectArray = [[NSMutableArray alloc] init];
                for (ProjectList *lsit in get.projectList) {
                    [_menuList addObject:lsit.projectName];
                    [_menuArr addObject:lsit];
                    [arr addObject:lsit.projectCode];
                    ProjectModel *model = [[ProjectModel alloc] init];
                    model.projectCode = lsit.projectCode;
                    model.projectName = lsit.projectName;
                    model.projectId = lsit.projectId;
                    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:model];
                    [projectArray addObject:data];
                }
                [userdf setObject:projectArray forKey:@"projectArray"];
                NSString *projectCode = [userdf objectForKey:@"projectCode"];
                for (int i = 0; i < arr.count; i++) {
                    NSString *pro = [arr objectAtIndex:i];
                    if ([pro isEqualToString:projectCode]) {
                        [userdf setObject:[NSString stringWithFormat:@"%d",i] forKey:@"indexString"];
                        [userdf synchronize];
                    }
                }
            }
            [[MerchantResourceVModel merchantResourceVModel] startMerchantResourceVModel];
        } else {
            if ([result.resultData.result isEqualToString:@"1"]) {
                if ([NSString isStringEmpty2:result.resultData.errorMsg] == NO) {
                    [self showToast:@"无项目权限，请联系管理员"];
                }
            }
            NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
            NSString *projectCode = [userdf objectForKey:@"projectCode"];
            if ([NSString isStringEmpty2:projectCode] == NO) {
                [self showToast:result.resultData.errorMsg];
            }
            
            /*
             提示语：账号权限发生变动，请重新登录
             code随机18位唯一码：108E65843mYuwqb01X
             //YUplf0wyU5vPVssLSG 对应的异地登录退出登录
             */
            
            if ([result.resultData.errorCode isEqualToString:@"YUplf0wyU5vPVssLSG"] || [result.resultData.errorCode isEqualToString:@"108E65843mYuwqb01X"]) {
                NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
                NSDictionary *dictionary = [defs dictionaryRepresentation];
                for(NSString *key in [dictionary allKeys]){
                    if ([key isEqualToString:@"DeviceToken123"] ||
                        [key isEqualToString:@"loginText"] ||
                        [key isEqualToString:@"provinceCityDistrict"]) {
                    }else {
                        [defs removeObjectForKey:key];
                        [defs synchronize];
                    }
                }
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:result.resultData.errorMsg preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    [appInstance showLogin];
                }];
                [alertController addAction:cancelAction];
                [self presentViewController:alertController animated:YES completion:nil];
            }
        }
    } failure:^(YTKBaseRequest *request) {
        [self showToast:@"连接服务器失败，请检查网络！"];
        [self hideHud];
    }];
}

#pragma mark - 导航
- (void)creatNavigationController {
    [self updateNewNavBar];
    NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
    NSString *token = [userdf objectForKey:@"is_login"];
    NSString *projectName;
    if ([NSString isStringEmpty2:token] == NO) {
       projectName  = [userdf objectForKey:@"projectName"];
    }

    NavigationView *view = [[NavigationView alloc] initWithFrame:CGRectMake(0, 0, EMM_WIDTH, 44) title:projectName colo:@"1"];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    [button addTarget:self action:@selector(showPopover:) forControlEvents:UIControlEventTouchUpInside];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    button.frame = CGRectMake(view.frame.size.width/2-50, 10, view.frame.size.width/2, 30.0);
    button.titleLabel.font = [UIFont systemFontOfSize:16];
    button.tag = 101;
    button.titleLabel.textAlignment = NSTextAlignmentCenter;
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [view addSubview:button];
    [self.navigationItem setTitleView:view];
}

#pragma mark - 点击选择项目触发的Button
- (void)showPopover:(UIButton *)button {
    if (_isShowUI == YES) {
        [self removeSubView];
        [self creatView];
        _isShowUI = NO;
    }else {
        [self removeSubView];
        _isShowUI = YES;
    }
}

#pragma mark - 初始化项目列表
- (void)creatView {
    NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
    NSString *num = [userdf objectForKey:@"indexString"];
    NSInteger h = 0;
    if (_menuList.count > 6) {
        h = 6*50;
    }else {
        h = _menuList.count * 50;
    }
    _menu = [[MenuLitsView alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight, EMM_WIDTH, EMM_HEIGHT-SafeAreaTopHeight) items:_menuList indet:num isShowUI:YES guodu:h];
    _menu.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    [[UIApplication sharedApplication].keyWindow addSubview:_menu];
    __weak MenuLitsView *weakSelf = _menu;
    [weakSelf setMenuLitsBlock:^(NSString *title, NSString *indet) {
        if ([NSString isStringEmpty2:title] == NO) {
            _isShowUI = YES;
        }else {
            _isShowUI = YES;
        }
        if ([NSString isStringEmpty2:indet] == NO) {
            ProjectList *lsit1 = _menuArr[[indet intValue]];
            NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
            [userdf setObject:lsit1.projectCode forKey:@"projectCode"];
            [userdf setObject:lsit1.projectId forKey:@"projectId"];
            [userdf setObject:lsit1.projectName forKey:@"projectName"];
            [userdf setObject:indet forKey:@"indexString"];
            [userdf synchronize];
            [self creatNavigationController];
            [self postGetProjectBusinessListApi];
            [[MerchantResourceVModel merchantResourceVModel] startMerchantResourceVModel];

        }
        [weakSelf removeFromSuperview];
    }];
}

#pragma mark - 删除弹出选择列表界面
- (void)removeSubView {
    [_menu removeFromSuperview];
    _menu = nil;
}

#pragma mark - 首页列表Api请求
- (void)postGetProjectBusinessListApi{
   
    [self showHudInWindow:@"正在加载请稍等..."];
    GetProjectBusinessListApi *api = [[GetProjectBusinessListApi alloc] initWith];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        GetProjectBusinessListApi *result = (GetProjectBusinessListApi *)request;
        if (result.isSuccess) {
             [_dataArr removeAllObjects];
            GetProjectBusinessList *get = result.resultData;
            for (HomePageList *list in get.homePageList) {
                [_dataArr addObject:list];
            }
//            HomePageList *model = [[HomePageList alloc]init];
//            model.homePageName = @"认购";
//            [_dataArr addObject:model];
//            
//            HomePageList *model1 = [[HomePageList alloc]init];
//            model1.homePageName = @"签约";
//            [_dataArr addObject:model1];
            
            _getProjectBusinessList = get;
            if (_dataArr.count > 0) {
                _homeTableView.hidden = NO;
            }else {
                _homeTableView.hidden = YES;
                UILabel *l = [[UILabel alloc] initWithFrame:CGRectMake(0, EMM_HEIGHT/2-100, EMM_WIDTH, 20)];
                l.text = @"当前没有记录";
                l.textAlignment = NSTextAlignmentCenter;
                l.font = [UIFont systemFontOfSize:14];
                [self.view addSubview:l];
            }
        } else {
            NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
            NSString *projectCode = [userdf objectForKey:@"projectCode"];
            if ([NSString isStringEmpty2:projectCode] == NO) {
                [self showToast:result.resultData.errorMsg];
            }

            /*
             提示语：账号权限发生变动，请重新登录
             code随机18位唯一码：108E65843mYuwqb01X
             //YUplf0wyU5vPVssLSG 对应的异地登录退出登录
             */
            
            if ([result.resultData.errorCode isEqualToString:@"YUplf0wyU5vPVssLSG"] || [result.resultData.errorCode isEqualToString:@"108E65843mYuwqb01X"]) {
                NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
                NSDictionary *dictionary = [defs dictionaryRepresentation];
                for(NSString *key in [dictionary allKeys]){
                    if ([key isEqualToString:@"DeviceToken123"] ||
                        [key isEqualToString:@"loginText"] ||
                        [key isEqualToString:@"provinceCityDistrict"]) {
                    }else {
                        [defs removeObjectForKey:key];
                        [defs synchronize];
                    }
                }
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:result.resultData.errorMsg preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    [appInstance showLogin];
                }];
                [alertController addAction:cancelAction];
                [self presentViewController:alertController animated:YES completion:nil];
            }
        }
        [self hideHud];
        [_homeTableView reloadData];
    } failure:^(YTKBaseRequest *request) {
        [_homeTableView reloadData];
        [self showToast:@"连接服务器失败，请检查网络！"];
        [self hideHud];
    }];
}

#pragma mark - UITableView 代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellId = @"HomeCellId";
    HomeCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"HomeCell" owner:self options:nil] lastObject];
    }
    cell.backgroundColor = [UIColor whiteColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (_dataArr.count > 0) {
        HomePageList *list = [_dataArr objectAtIndex:indexPath.row];
        cell.titleLbale.text = list.homePageName;
        if ([NSString isStringEmpty2:list.homePageNoReadNum] == NO) {
            if (![list.homePageNoReadNum isEqualToString:@"0"]) {
                cell.numLabel.layer.masksToBounds = YES;
                cell.numLabel.layer.cornerRadius = 12;
                cell.numLabel.backgroundColor = [UIColor colorFromHexCode:@"#f87242"];
                cell.numLabel.text = list.homePageNoReadNum;
            }
        }
        if ([list.homePageName isEqualToString:@"逾期未签约"]) {
            cell.titleImageView.image = [UIImage imageNamed:@"hom_ico1"];
        }else if ([list.homePageName isEqualToString:@"逾期未付款"]) {
            cell.titleImageView.image = [UIImage imageNamed:@"hom_ico2"];
        }else if ([list.homePageName isEqualToString:@"待处理客户"]) {
            cell.titleImageView.image = [UIImage imageNamed:@"hom_ico3"];
        }else if ([list.homePageName isEqualToString:@"审核申请"]) {
            cell.titleImageView.image = [UIImage imageNamed:@"hom_ico6"];
        }else if ([list.homePageName isEqualToString:@"公告"]) {
            cell.titleImageView.image = [UIImage imageNamed:@"hom_ico4"];
        }else if ([list.homePageName isEqualToString:@"提醒"]) {
            cell.titleImageView.image = [UIImage imageNamed:@"hom_ico5"];
        }else if ([list.homePageName isEqualToString:@"下次跟进提醒"]) {
            cell.titleImageView.image = [UIImage imageNamed:@"hom_ico7"];
        }else if ([list.homePageName isEqualToString:@"未完善信息客户"]) {
            cell.titleImageView.image = [UIImage imageNamed:@"hom_ico8"];
        }else if ([list.homePageName isEqualToString:@"签约回款提醒"]) {
            cell.titleImageView.image = [UIImage imageNamed:@"backMoneyType"];
        }else if ([list.homePageName isEqualToString:@"认购"]) {
            cell.titleImageView.image = [UIImage imageNamed:@"Shape"];
        }else if ([list.homePageName isEqualToString:@"签约"]) {
            cell.titleImageView.image = [UIImage imageNamed:@"CombinedShape"];
        }
    }
    return cell;
}

#pragma mark -tableViewcell点击调用的方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    HomePageList *list = [_dataArr objectAtIndex:indexPath.row];
    if ([list.homePageName isEqualToString:@"逾期未签约"]) {
        TouristsWebController *evc = [[TouristsWebController alloc] init];
        evc.hidesBottomBarWhenPushed = YES;
        evc.titleString = @"逾期未签约";
        evc.TouristType = None_QianYue;
        [self.navigationController pushViewController:evc animated:YES];
    }else if ([list.homePageName isEqualToString:@"逾期未付款"]) {
        TouristsWebController *evc = [[TouristsWebController alloc] init];
        evc.hidesBottomBarWhenPushed = YES;
        evc.titleString = @"逾期未付款";
        evc.TouristType = None_FuKuan;
        [self.navigationController pushViewController:evc animated:YES];
    }else if ([list.homePageName isEqualToString:@"待处理客户"]) {
        EMMTouristsViewController *evc = [[EMMTouristsViewController alloc] init];
        evc.hidesBottomBarWhenPushed = YES;
        evc.titleString = @"待处理客户";
        evc.tourSring = @"1";
        evc.tpye = @"1";
        [self.navigationController pushViewController:evc animated:YES];
    }else if ([list.homePageName isEqualToString:@"审核申请"]) {
        ExamineListViewController *evc = [[ExamineListViewController alloc] init];
        evc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:evc animated:YES];
    }else if ([list.homePageName isEqualToString:@"公告"]) {
        NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
        NSString *projectCode = [userdf objectForKey:@"projectCode"];
        NoticeViewController *evc = [[NoticeViewController alloc] init];
        evc.hidesBottomBarWhenPushed = YES;
        evc.isNot = YES;
        evc.projectCode = projectCode;
        [self.navigationController pushViewController:evc animated:YES];
    }else if ([list.homePageName isEqualToString:@"提醒"]) {
        RemindViewController *rvc = [[RemindViewController alloc] init];
        rvc.hidesBottomBarWhenPushed = YES;
        rvc.isNot = YES;
        [self.navigationController pushViewController:rvc animated:YES];
    }else if ([list.homePageName isEqualToString:@"下次跟进提醒"]) {
        NextReminderViewController *evc = [[NextReminderViewController alloc] init];
        evc.hidesBottomBarWhenPushed = YES;
        evc.isNextReminder = YES;
        [self.navigationController pushViewController:evc animated:YES];
    }else if ([list.homePageName isEqualToString:@"未完善信息客户"]) {
        EMMTouristsViewController *evc = [[EMMTouristsViewController alloc] init];
        evc.hidesBottomBarWhenPushed = YES;
        evc.titleString = @"未完善信息客户";
        evc.tourSring = @"0";
        evc.tpye = @"4";
        [self.navigationController pushViewController:evc animated:YES];
    }else if ([list.homePageName isEqualToString:@"签约回款提醒"]) {
        SignBackMoneyController *backMoney = [[SignBackMoneyController alloc]init];
        backMoney.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:backMoney animated:YES];
    }else if ([list.homePageName isEqualToString:@"认购"]) {
        DealsRecordController *dealsRecord = [[DealsRecordController alloc]init];
        dealsRecord.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:dealsRecord animated:YES];
       
    }else if ([list.homePageName isEqualToString:@"签约"]) {
        DealsRecordController *dealsRecord = [[DealsRecordController alloc]init];
        dealsRecord.hidesBottomBarWhenPushed = YES;
        dealsRecord.typeFlag = YES;
        [self.navigationController pushViewController:dealsRecord animated:YES];
    }
    
}

@end
